// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { TreeSelect,Table,Form,Radio,Tree, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './predictListStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid } from 'widget/Grid/index'
import moment from 'moment';

const FormItem = Form.Item
const { RangePicker } = DatePicker
const { Option } = Select;
const { TreeNode } = Tree
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const predictListView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll  } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let { proId,distributionNameList,id,tableShow,treeObj,treeList,treeKeys,tableData,keys,tableObj,query, actionType, btnLoading,loading } = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  const columns = [
    {
      title: '主数据产品类型', dataIndex: 'mdmProductType', key: 'mdmProductType',
      render: function (value, item, index) {
        return <div>
                {/* <FormItem style={{marginBottom: 0}}>
                      {getFieldDecorator(`mdmProductType_${index}`, {
                          rules: [{
                            required: false,whitespace: true, message: '请选择主数据产品类型'
                          }],
                          initialValue: item.mdmProductType,
                      })( */}
                        <TreeSelect
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        value={item.mdmProductType}
                        treeData={distributionNameList}
                        placeholder="请选择主数据产品类型"
                        treeDefaultExpandAll
                        onChange={(value,label)=>{tableChange(value,label,'mdmProductType',item.key)}}
                      />
                      {/* )}
                  </FormItem> */}
            </div>
      }
    }, 
    {
      title: '主数据产品类型编码', dataIndex: 'mdmCode', key: 'mdmCode',
      render: function (value, item, index) {
        return item.mdmCode
      }
    }, 
    {
      title: '创建人', dataIndex: 'creator', key: 'creator',
      render: function (value, item, index) {
        return item.creator
      }
    }, 
    {
      title: '创建时间', dataIndex: 'createTime', key: 'createTime',
      render: function (value, item, index) {
        return item.createTime
      }
    }, 
  ]
  const columns1 = [
    {
      title: '编码', dataIndex: 'proCode', key: 'proCode',
      render: function (value, item, index) {
        return item.proCode
      }
    }, 
    {
      title: '名称', dataIndex: 'proName', key: 'proName',
      render: function (value, item, index) {
        return item.proName
      }
    }
  ]
  // const expandedRowRender = () => {
  //   const columns2 = [
  //     { title: 'Date', dataIndex: 'date', key: 'date' },
  //     { title: 'Name', dataIndex: 'name', key: 'name' },
  //   ];

  //   const data = [];
  //   for (let i = 0; i < 3; ++i) {
  //     data.push({
  //       key: i,
  //       date: '001',
  //       name: 'name',
  //     });
  //   }
  //   return <Table columns={columns2} dataSource={data} pagination={false} showHeader={false}/>;
  // };

  function treeRowClick(e,record){
    tableShow = true
    id = record.key?record.key:record.proId
    proId= record.proId
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableShow,id,proId}
    })
    if(record.proId){
      dispatch({
        type: `${namespace}/queryInfo`,
        payload: {id:proId}
      })
    }else{
      query.productTabName ='一级菜单',//分类
      query.productStatus = '0', //状态
      query.productCode ='', //产品状编码
      query.productName = '',//字段名称
      query.ProductType = []
      tableData = []
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {query,tableData}
      })
    }
    form.resetFields()
  }
  // 表格配置------------开始
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: [].concat(columns, generateAction())
      ,//已发布的活动不能添加和删除时间段
      pageConfig:{},
      tableData: {total: '',dataSource: tableData},
      selectedRowKeys:'',
    },
    scroll: { x: '60%' },
    paginationFlag : false,
    loading
  }


  // 表格操作区域
  function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 120,
      render: (data, record, index) => {
        return (
          actionType == 'check'?null:
          <span>
              <a href='javascript:void(0)' onClick={() => {deleteItem(data,record, index)}}>
                删除
              </a>
          </span>
        )
      }
    }
  }
  // 添加
  function addTableRow(type){
    if(type == '主数据'){
      tableObj.key = ++keys
      let obj = JSON.parse(JSON.stringify(tableObj))
      tableData.push(obj)
  
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {tableData,keys}
      })
    }
    if(type == 'tree'){
      treeObj.key = ++treeKeys
      let obj = JSON.parse(JSON.stringify(treeObj))
      treeList.push(obj)
      tableShow = true
      query.productTabName ='一级菜单',//分类
      query.productStatus = '0', //状态
      query.productCode ='', //产品状编码
      query.productName = '',//字段名称
      query.ProductType = []
      tableData = []
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {treeList,treeKeys,tableShow,query}
      })
    }
  }

  //删除选中行
  function deleteItem(data,record) {
    let arr = tableData&&tableData.length?tableData.filter(item => item.key != data.key):[]
    tableData = arr
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }
  //删除
  function deleteFun() {
    if(proId){
      dispatch({
        type: `${namespace}/deleteFun`,
        payload: {}
      })
    }else{
      treeList = treeList.length?treeList.filter(item => item.key!= id):[]
    }

    tableShow = false
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {treeList,tableShow}
    })
  }

  //输入框改变时
  function inputChange(e, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: e,
        }
      }
    })
    let type =''
    if(name=='productName'){
      type = "proName"
    }
    for(var item of treeList){
      let key = item.proId?item.proId:item.key
      if(key== id){
        item[type] = e
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {treeList}
    })
  }
  //表格改变时
  function tableChange (value,label,name,id) {
      Date.prototype.Format = function (fmt) { // author: meizz
          var o = {
              "M+": this.getMonth() + 1, // 月份
              "d+": this.getDate(), // 日
              "h+": this.getHours(), // 小时
              "m+": this.getMinutes(), // 分
              "s+": this.getSeconds(), // 秒
              "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
              "S": this.getMilliseconds() // 毫秒
          };
          if (/(y+)/.test(fmt))
              fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
          for (var k in o)
              if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                  return fmt;
      }
      let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
      let parentId
      for(var pp of distributionNameList){
        for(var q of pp.children){
          if(q.value == value){
            parentId = q.parentId
          }
        }
      }
      for(var item of tableData){
        if(item.key == id){
          item.mdmProductType = label[0]
          item.mdmCode = value
          item.creator = localStorage.username
          item.createTime =  dateTime
          item.mdmParentId =  parentId
        }
      }
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {tableData}
      })
  }
  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {}
        })
      }
    })
  }
  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button  style={{background: '#ff91c5',color:'#fff'}} onClick={e => deleteFun()} loading={btnLoading}>删除</Button>
        <Button  type='primary' onClick={e => submit()} loading={btnLoading}>保存</Button>
      </div>
      <CollapsiblePanels title=" "   style={{position: 'relative'}}>
        <Button style={{marginBottom:'20px'}}    type='primary' onClick={() => { addTableRow('tree') }}>新增一级</Button>
        <Row className={styles.ziyuanWrap} gutter={16}>
          <Col span={8} className={styles.gridConter}>
            <div className="title" style={{hieght: '28px',lineHeight:'28px',paddingLeft:'12px',background: '#f4f4f4',marginBottom:'12px'}}>前策产品类型结构</div> 
            <Table
              className="components-table-demo-nested"
              columns={columns1}
              // expandedRowRender={expandedRowRender}
              pagination={false} 
              dataSource={treeList}
              rowClassName={'rowClassName'}
              onRow={record => {
                return {
                  onClick: e => {treeRowClick(e,record)}, // 点击行
                };
              }}
            />
          </Col>
          <Col span={16} className={styles.gridConter} style={{display: tableShow?"block":"none"}}>
            <div className="title" style={{hieght: '28px',lineHeight:'28px',paddingLeft:'12px',background: '#f4f4f4',marginBottom:'12px'}}>产品类型信息</div>
            <Row>
              <Col span={12}>
                <FormItem label='分类'  {...formItemLayoutPro}>
                  {getFieldDecorator('productTabName', {
                    rules: [{
                      required: true, whitespace: true, message: '请输入分类'
                    }],
                    initialValue: query.productTabName
                  })(
                    <Input disabled={true} placeholder='请输入分类'  onChange={(e) => { inputChange(e.target.value, 'productTabName') }} />
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label='编码'  {...formItemLayoutPro}>
                  {getFieldDecorator('productCode', {
                    rules: [{
                      required: false, whitespace: true, message: '请输入编号',
                    }],
                    initialValue: query.productCode+''
                  })(
                    <Input disabled={true} placeholder='请输入编号'  onChange={(e) => { inputChange(e.target.value, 'productCode') }} />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <FormItem label='字段名称'  {...formItemLayoutPro}>
                  {getFieldDecorator('productName', {
                    rules: [{
                      required: true, whitespace: true, message: '请输入字段名称'
                    }],
                    initialValue: query.productName
                  })(
                    <Input  placeholder='请输入字段名称'  onChange={(e) => { inputChange(e.target.value, 'productName') }} />
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem label='状态'  {...formItemLayoutPro}>
                  {getFieldDecorator('productStatus', {
                    rules: [{
                      required: true, whitespace: true, message: '请选择状态',
                    }],
                    initialValue: query.productStatus
                  })(
                    <Select  placeholder='请选择状态' onChange={(e) => { inputChange(e, 'productStatus') }}>
                      <Select.Option value='0'>启用</Select.Option>
                      <Select.Option value='1'>禁用</Select.Option>
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row style={{marginBottom: '12px'}}>
              <Col span={12}>
                <Col span={6} style={{textAlign:'right',paddingRight:'14px'}}>
                关联主数据产品
                </Col>
                  <Button  type='primary' onClick={() => { addTableRow('主数据') }}>新增</Button>
              </Col>
            </Row>
            <div className={'mt1', 'table_projectList'} style={{paddingLeft:'12.6%',paddingRight:'8%'}}>
              <Form>
                <Grid {...gridProps}/>
              </Form>
            </div>
          </Col>
        </Row>          
      </CollapsiblePanels>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(predictListView))